﻿using Domain.Entities;
using SqlSugar;
using System.Reflection;
using System.Xml.Linq;

namespace WorldSystem.Api.Helpers
{
    public class SqlSugarHelper
    {
        public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig()
        {
            //ConnectionString= "DataSource=world_system.db",
            ConnectionString = "Server=localhost;Database=WorldSystem;User ID=sa;Password=123456;Trusted_Connection=True;",
            //ConnectionString = "data source=localhost;Initial Catalog=WorldSystem;User ID=sa;Password=123456;MultipleActiveResultSets=true",
            DbType = DbType.SqlServer,
            IsAutoCloseConnection = true,
        }, db =>
        {
            //(A)全局生效配置点，一般AOP和程序启动的配置扔这里面 ，所有上下文生效
            //调试SQL事件，可以删掉
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响

                //获取原生SQL推荐 5.1.4.63  性能OK
                //UtilMethods.GetNativeSql(sql,pars)

                //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)

            };

            //多个配置就写下面
            //db.Ado.IsDisableMasterSlaveSeparation=true;

            //注意多租户 有几个设置几个
            //db.GetConnection(i).Aop
        });

        ////(B)当前上下文生效配置点,一般多租户相关操作写在这儿 
        ////db.GetConnectionxxx 只在当前上下文有效，不会共享
        ////如果是程序启动时的配置全部到A里面去

        ////建表
        ////db.CodeFirst.InitTables<Student>(); 更多看文档迁移   

        ////查询表的所有
        //var list = SqlSugarHelper.Db.Queryable<Student>().ToList();

        ////插入
        //SqlSugarHelper.Db.Insertable(new Student() { SchoolId = 1, Name = "jack" }).ExecuteCommand();

        ////更新
        //SqlSugarHelper.Db.Updateable(new Student() { Id = 1,SchoolId = 2,Name = "jack2" }).ExecuteCommand();

        ////删除
        //SqlSugarHelper.Db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();
        public static void CodeFirst()
        {

            //建库：如果不存在创建数据库 存在不会重复创建 
            
            Db.DbMaintenance.CreateDatabase(); // 注意 ：Oracle和个别国产库需不支持该方法，需要手动建库 

            Db.CodeFirst.SetStringDefaultLength(255);

            
            Type[] tables = Assembly.Load("Domain").DefinedTypes.Where(p=>p.Namespace=="Domain.Entities").ToArray();
            
            //先删除后重建
            //Db.DbMaintenance.DropTable(tables);
            Db.CodeFirst.InitTables(tables);

            if (Db.Queryable<UserInfo>().Count() == 0)
            {
                UserInfo insertObj = new UserInfo()
                {
                    UserName = "admin",
                    Pwd = "123456",
                };
                Db.Insertable(insertObj).ExecuteCommand(); //都是参数化实现

                Role role = new Role()
                {
                    RoleName = "管理员"
                };
                Db.Insertable(insertObj).ExecuteCommand(); //都是参数化实现
            }

        }
    }
}
